<template>
    <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="suName">
            <el-input v-model="ruleForm.suName" @blur="querybyname"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="suPwd">
            <el-input type="password" v-model="ruleForm.suPwd" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
            <el-input type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="roleName">
            <el-select v-model="ruleForm.roleName"  placeholder="请选择角色">
                <el-option
                        v-for="item in role"
                        :key="item.id"
                        :label="item.roleName"
                        :value="item.id">
                </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="上传图片">
            <el-upload
                    list-type="picture-card"
                    action="#"
                    :limit="1"
                    :auto-upload="false"
                    :accept="accept"
                    :on-change="changeImag"
                    :on-exceed="handleExceed"
                    :before-remove="beforeRemove">
                <i class="el-icon-plus"></i>
            </el-upload>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
    </el-form>
</template>
<script>

    let pwd02 = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/

    export default {
        data() {
            var checkAge = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('年龄不能为空'));
                }
                setTimeout(() => {
                    if (!Number.isInteger(value)) {
                        callback(new Error('请输入数字值'));
                    } else {
                        if (value < 18) {
                            callback(new Error('必须年满18岁'));
                        } else {
                            callback();
                        }
                    }
                }, 1000);
            };
            var validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'));
                } else {
                    if (this.ruleForm.checkPass !== '') {
                        this.$refs.ruleForm.validateField('checkPass');
                    }
                    callback();
                }
            };
            var validatePass2 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'));
                } else if (value !== this.ruleForm.suPwd) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };
            return {
                img:"",
                accept: ".jpg,.png",//上传格式限制
                ruleForm: {
                    suName:'',
                    suPwd: '',
                    checkPass: '',
                    roleName:"",
                },
                role:[],
                rules: {
                    roleName: [
                        { required: true, message: '请选择角色', trigger: 'change' }
                    ],
                    suPwd: [
                        {required: true, validator: validatePass, trigger: 'blur' }
                    ],
                    checkPass: [
                        {required: true, validator: validatePass2, trigger: 'blur' }
                    ],
                    age: [
                        {required: true, validator: checkAge, trigger: 'blur' }
                    ],
                    suName: [
                        { required: true, message: '请输入用户名', trigger: 'blur' },
                        { min: 5, max: 10, message: '长度在 5 到 10 个字符', trigger: 'blur' }
                ]
                }
            };
        },
        methods: {
            submitForm(formName) {
                if (pwd02.test(this.ruleForm.checkPass)){
                    this.$refs[formName].validate((valid) => {
                        if (valid) {
                            //数据组装
                            let staffForm = new FormData();

                            this.role.forEach(itme=>{
                                if (this.roleName == itme.roleName){
                                    staffForm.append("id",itme.id)
                                }
                            })

                            Object.keys(this.ruleForm).forEach(key=>{
                                staffForm.append(key,this.ruleForm[key])
                            })

                            staffForm.append("img",this.img.raw)

                            //调用异步，进行申请
                            this.$axios({
                                method: 'post',
                                url: "addbySystem.action",
                                data: staffForm,
                                headers: {
                                    'Content-Type': 'multipart/form-data'
                                }
                            }).then(res => {
                                if(res.data.msg=="添加成功"){
                                    this.$message.success(res.data.msg);
                                    this.resetForm("ruleForm");//重置表单
                                    this.img="";//重置图像
                                    this.roleName=""
                                    this.$parent.$parent.getdata()
                                    this.$parent.$parent.dialogVisible=false
                                }else {
                                    this.$message.error(res.data.msg)
                                }
                            }).catch(err => {
                                this.$message.warning(err);
                            })

                        } else {
                            console.log('error submit!!');
                            return false;
                        }
                    });
                }else {
                    this.$message.warning("密码输入有误必须包含字符大于或等于8位数!!")
                }

            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },
            handleExceed(files, fileList) {
                this.$message.warning(`只能选择一个头像`)
            },
            beforeRemove(file, fileList) {
                if (this.$confirm(`确定移除 ${file.name}？`)) {
                    this.img = file;
                }
            },
            changeImag(file, fileList) {
                //获取文件信息
                this.img = file;
            },
            //判断重复
            querybyname(){
              let name =this.ruleForm.suName;
              let users = new URLSearchParams();
              users.append("suName",name)
              this.$axios.post("querybyname.action",users).
              then(request=>{
                  if (request.data.msg=="重复"){
                      this.ruleForm.suName=""
                      this.$message.warning("重复的用户名")
                  }
              }).
              catch()
            },
            //获取角色
            getroles(){
                this.$axios.post("queryallroles.action").
                then(request=>{
                    let role = request.data.filter(item=>{
                        return  item.roleName!="供货商" && item.roleName!="商户" && item.roleName!="普通用户"
                    })
                    this.role = role
                }).
                catch()
            }

        },
        created() {
            this.getroles()
        }
    }
</script>

<style scoped>

</style>